package cn.szabadsag.hrm.mqconsumer;

import cn.szabadsag.hrm.config.RabbitMQConfig;
import cn.szabadsag.hrm.dto.KillOrderDto;
import cn.szabadsag.hrm.dto.OrderDelayMessage2MQDto;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * 订单延迟消息处理
 * @author yangcong
 * @date 2022年04月22日 22:55
 * @since
 */
@Component
@Slf4j
public class OrderDelayMessageHandler {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 从死信队列获取消息
     * @param dto
     */
    @RabbitListener(queues = RabbitMQConfig.NAME_QUEUE_ORDER_DEAD)
    public void handler(@Payload OrderDelayMessage2MQDto dto, Message message, Channel channel){
        if (dto == null)return;
        //  1.拿到预创订单
        String key = "killorder:" + dto.getOrderNo() + ":" + dto.getLoginId();
        //  加锁  porder:表示预创订单
        RLock lock = redissonClient.getLock("porder" + dto.getOrderNo());
        lock.lock();
        log.info("处理订单超时------加锁........");
        try {
            KillOrderDto orderDto = (KillOrderDto) redisTemplate.opsForValue().get(key);
            //  2.如果没有，不管
            if (orderDto == null)return;
            //  3.如果有，说明超时，退库存
            RSemaphore semaphore = redissonClient.getSemaphore("store:" + dto.getKillId());
            semaphore.addPermits(1);
            //  4.删除用户的秒杀记录
            String killLog = "log:" + dto.getLoginId() + ":" + dto.getKillId();
            redisTemplate.delete(killLog);
            redisTemplate.delete(key);
            log.info("下单超时，退库存 {}", orderDto);
        }finally {
            if (lock.isLocked())lock.unlock();
            log.info("处理订单超时------释放锁........");
        }

    }















}
